﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Generator.Tools
{
    public partial class StringFormat : Form
    {

        private int _trimStatus = 0;
        private int _newLineType = 0;
        public StringFormat()
        {
            InitializeComponent();
        }


        private void FormatString()
        {
            rtResult.Text = "";
            var format = GetFormatText();
            string optionEnter = string.Empty;
            //if (chkEnter.Checked)
            //{
            //    optionEnter = "\"+  Environment.NewLine + " + Environment.NewLine + "\"";
            //}


            var sepChar = GetSepChar();

            string[] lines = null;
            if (_newLineType == 0)
            {
                lines = rtSource.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            }
            else {
                lines = rtSource.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            }

            foreach (var txt in lines)
            {
                if (txt.Trim().Length == 0)
                    continue;

                string[] strs = txt.Split(new char[] { sepChar });
                string[] strToFormat = new string[Math.Max(format.Item2, strs.Length)];

                for (int i = 0; i < strs.Length; i++)
                {
                    string[] ml = strs[i].Split(Environment.NewLine.ToCharArray(), StringSplitOptions.None);
                    if (ml.Length > 1)
                    {

                        strToFormat[i] = ml.Aggregate((workingSentence, next) =>
                                                    workingSentence + optionEnter + next);
                    }
                    else
                    {
                        if (_trimStatus == 1) {
                            strToFormat[i] = strs[i].TrimStart(null);
                        }
                        else if (_trimStatus == 2)
                        {
                            strToFormat[i] = strs[i].Trim();
                        }
                        else if (_trimStatus == 3)
                        {
                            strToFormat[i] = strs[i].TrimEnd(null);
                        }
                        else
                        {
                            strToFormat[i] = strs[i];// i == 0 ? strs[i] : "\t" + strs[i];
                        }
                    }
                }

                try
                {
                    string tmpStr = string.Format(format.Item1, strToFormat);
                    rtResult.AppendText(tmpStr);
                }
                catch (Exception ex)
                {
                    rtResult.AppendText(ex.Message);
                    rtResult.AppendText(Environment.NewLine);
                    rtResult.AppendText("--------------------------------------------------");
                }
            }

        }

        private char GetSepChar()
        {
            if (string.IsNullOrEmpty(toolStripComboBox1.Text))
            {
                return '\t';
            }

            if (toolStripComboBox1.Text.ToUpper() == "{TAB}")
            {
                return '\t';
            }

            if (toolStripComboBox1.Text.Length > 0)
            { 
                char c;
                if (char.TryParse(toolStripComboBox1.Text.Substring(0, 1), out c))
                {
                    return c;
                }
            }

            return '\t';
        }

        private Tuple<string, int> GetFormatText()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(rtFormat.Text.Replace("{", "{{").Replace("}", "}}"));

            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\{\d+\}");
            var matches = reg.Matches(sb.ToString());
            for (int i = matches.Count - 1; i >= 0; i--)
            {
                var match = matches[i];
                var newValue = match.Value.Substring(1, match.Value.Length - 2);
                sb.Remove(match.Index, match.Length);
                sb.Insert(match.Index, newValue);
            }
            return new Tuple<string, int>(sb.ToString(), matches.Count);
        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            FormatString();
        }

        private void tsTrim_Click(object sender, EventArgs e)
        {
            _trimStatus = Convert.ToInt32(((ToolStripButton)sender).Tag);
            SetTrimButtonStatus(_trimStatus);
        }

        private void SetTrimButtonStatus(int trimStatus)
        {
            tsTrimNone.Checked = trimStatus == 0;
            tsTrimLeft.Checked = trimStatus == 1;
            tsTrimAll.Checked = trimStatus == 2;
            tsTrimRight.Checked = trimStatus == 3;
        }

        private void SetLineTypeButtonStatus(int lineType)
        {
            tsbWindowsLine .Checked = lineType == 0;
            tsbUnixLine .Checked = lineType == 1; ;
        }

        private void tsLineType_Click(object sender, EventArgs e)
        {
            _newLineType = Convert.ToInt32(((ToolStripButton)sender).Tag);
            SetLineTypeButtonStatus(_newLineType);
        }

    }
}
